package com.cindata

import com.cindata.dictionary.*
import com.cindata.dimension.*
import grails.converters.JSON
import grails.transaction.Transactional
import org.springframework.security.access.annotation.Secured

import java.text.SimpleDateFormat

import static org.springframework.http.HttpStatus.*

@Secured(['isAuthenticated()'])
@Transactional
class EstateController
{
    def apiService
    def springSecurityService
    def splitMatchApiService
    def collateralService
    def evaluateService

    static allowedMethods = [save: "POST", update: "PUT", delete: "DELETE"]

    def index()
    {
        def max = Math.min(params.max ? params.max.toInteger() : 10, 100)
        def offset = params.offset ? params.offset.toInteger() : 0
        def communityId = params['communityId']
        if (communityId)
        {
            def cityNumber = Estate.findByCommunityId(communityId)?.city?.zoneNumber
            if (cityNumber)
            {
                params['city'] = cityNumber
            }
            def districtNumber = Estate.findByCommunityId(communityId)?.district?.zoneNumber
            if (districtNumber)
            {
                params['district'] = districtNumber
            }
        }
        def city = params["city"]
        def district = params["district"]
        def estateStatus = params["estateStatus"]
        def name = params["name"]
        def sourceAddress = params["sourceAddress"]
        def risk = params["risk"]
        def buildAreaStart = params["buildAreaStart"]
        def buildAreaEnd = params["buildAreaEnd"]
        def mortgageStatus = params["mortgageStatus"]
        def buildingType = params["buildingType"]
        def cashability = params["cashability"]
        def createdDateStart = params['createdDateStart']
        def createdDateEnd = params['createdDateEnd']
        def province = params["province"]
        def externalId = params['externalId']
        def batch = params["batch"]
        def latestEvaluateAccount = params["latestEvaluateAccount"]
        def report = params['report']
        def estateQueryParam = new HashMap()

        def user = User.findById(springSecurityService.principal.id)
        def estateSql = " from Collateral e where e.status = 'Completed' and e.type.code = 'estate' and e.account.id in " + Account.FilterAccountSql(user)
        def sql = " "
        if (city && city != "-1")
        {
            sql += " and e.city.zoneNumber = :city "
            estateQueryParam['city'] = city
        }
        if (district && district != "-1")
        {
            sql += " and e.district.zoneNumber = :district"
            estateQueryParam['district'] = district
        }
        if (estateStatus && estateStatus != "")
        {
            sql += " and e.estateStatus.id = :estateStatus"
            estateQueryParam['estateStatus'] = Long.parseLong(estateStatus)
        }
        if (batch && batch != "")
        {
            sql += " and e.estate.batch.id = :batch"
            estateQueryParam['batch'] = Long.parseLong(batch)
        }
        if (latestEvaluateAccount && latestEvaluateAccount != "")
        {
            sql += " and e.estate.latestEvaluateAccount.id = :latestEvaluateAccount"
            estateQueryParam['latestEvaluateAccount'] = Long.parseLong(latestEvaluateAccount)
        }
        if (name && name != "")
        {
            sql += " and e.name like :name "
            estateQueryParam['name'] = '%' + name + '%'
        }
        if (sourceAddress && sourceAddress != "")
        {
            sql += " and e.estate.sourceAddress like :sourceAddress "
            estateQueryParam['sourceAddress'] = '%' + sourceAddress + '%'
        }
        if (risk && risk != "")
        {
            def riskList = RiskDimension.list()
            riskList.each {
                if (it?.label == risk)
                {
                    def minValue = it.minValue / 100
                    def maxValue = it.maxValue / 100
                    sql += " and e.cltv > :minValue and e.cltv <= :maxValue "
                    estateQueryParam['minValue'] = minValue
                    estateQueryParam['maxValue'] = maxValue
                }
            }
        }
        if (buildAreaStart && buildAreaStart != '')
        {
            sql += " and e.estate.buildArea >= :buildAreaStart "
            estateQueryParam['buildAreaStart'] = new BigDecimal(buildAreaStart)
        }

        if (buildAreaEnd && buildAreaEnd != '')
        {
            sql += " and e.estate.buildArea <= :buildAreaEnd "
            estateQueryParam['buildAreaEnd'] = new BigDecimal(buildAreaEnd)
        }
        if (buildingType && buildingType != "")
        {
            sql += " and e.estate.buildingType.id = :buildingType "
            estateQueryParam['buildingType'] = Long.parseLong(buildingType)
        }
        if (cashability && cashability != "")
        {
            sql += " and e.cashability.id = :cashability "
            estateQueryParam['cashability'] = Long.parseLong(cashability)
        }
        if (communityId && communityId != '-1')
        {
            sql += " and e.estate.communityId = :communityId "
            estateQueryParam['communityId'] = Long.parseLong(communityId)
        }
        if (province && province != '-1')
        {
            sql += " and e.estate.province.name = :province "
            estateQueryParam['province'] = province
        }
        if (createdDateStart)
        {
            //中文日期转换
            def createdDateStarts = DateUtil.GetDateBeginByDateStr(createdDateStart)
            sql += "and e.estate.createdDate >=  :createdDateStarts "
            estateQueryParam['createdDateStarts'] = createdDateStarts
        }
        if (createdDateEnd)
        {
            //中文日期转换
            def createdDateEnds = DateUtil.GetNextDateBeginByDateStr(createdDateEnd)
            sql += "and e.estate.createdDate <=  :createdDateEnds "
            estateQueryParam['createdDateEnds'] = createdDateEnds
        }
        if (externalId && externalId != '-1')
        {
            sql += " and e.estate.externalId = :externalId "
            estateQueryParam['externalId'] = externalId
        }

        def countSql = " select count(e.id) from Collateral e where e.status = 'Completed' and e.type.code = 'estate' and e.account.id in " + Account.FilterAccountSql(user)
        countSql += sql
        sql += " order by e.externalId desc "
        estateSql += sql

        if (report == 'yes')
        {
            def collateralList = Collateral.executeQuery(estateSql, estateQueryParam)
            def estateImportBatch = new EstateImportBatch()
            estateImportBatch.batchNumber = params['numberTemp']
            estateImportBatch.evaluateType = EvaluateDict.findById(params['evaluateTypeTemp']?.toInteger())
            estateImportBatch.estateNum = collateralList?.size()
            estateImportBatch.type = "评估"
            estateImportBatch.importFileType = ImportFileTypeDict.findByCode("Estate")
            estateImportBatch.status = ExecStatusDict.UNEXECUTED()
            estateImportBatch.account = user?.account
            if (estateImportBatch.validate())
            {
                estateImportBatch.save flush: true
            }
            else
            {
                println estateImportBatch.errors
            }

            collateralList?.each {
                if (it?.estate)
                {
                    def batchEstate = new BatchEstate()
                    batchEstate.batch = estateImportBatch
                    batchEstate.estate = it?.estate
                    batchEstate.evaluateStatue = ExecStatusDict.UNEXECUTED()
                    if (batchEstate.validate())
                    {
                        batchEstate.save flush: true
                    }
                    else
                    {
                        println batchEstate.errors
                    }

                    it?.estate.batch = estateImportBatch
                    it?.estate?.save flush: true
                }
            }

            redirect controller: 'estateImportBatch', action: 'index'
            return
        }

        def collateralList = Collateral.executeQuery(estateSql, estateQueryParam, [max: max, offset: offset])
        def collateralCount = Collateral.executeQuery(countSql, estateQueryParam)
        def districtList = District.findAllByParentAreaAndAreaLevel(City.findByZoneNumberAndAreaLevel(city, 2), 3)
        respond collateralList, model: [collateralList: collateralList, collateralCount: collateralCount[0], districtList: districtList, params: params]
    }

    def show(Collateral collateral)
    {
        def estate = collateral?.estate
        def zoneNumber = estate?.city?.zoneNumber
        def communityId = estate?.communityId
        //小区详情
        def community = apiService.community(zoneNumber, communityId)
        //小区照片
        def communityPicArr = apiService.picture(zoneNumber, communityId, 5, 3)
        //成交案例列表
        def saleList = apiService.sale(zoneNumber, communityId)
        //挂牌案例列表
        def listings = apiService.listing(zoneNumber, communityId)
        // 贷款信息
        def mortgageList = MortgageCollateral.findAllByCollateral(collateral)*.mortgage

        def replaceCollateral = collateral?.replacementCollateral

        respond collateral, model: [params: params, showType: params['showType'], mortgageList: mortgageList, estateDetail: estate, community: community['data'], replaceCollateral: replaceCollateral, communityPicArr: communityPicArr['data'], saleList: saleList['data'], listings: listings['data']]
    }

    def mapShow(Estate estate)
    {
        def collateral = Collateral.findByEstate(estate)
        def zoneNumber = estate.city.zoneNumber
        def communityId = estate.communityId
        //小区详情
        def community = apiService.community(zoneNumber, communityId)
        //小区照片
        def communityPicArr = apiService.picture(zoneNumber, communityId, 5, 3)
        //成交案例列表
        def saleList = apiService.sale(zoneNumber, communityId)
        //挂牌案例列表
        def listings = apiService.listing(zoneNumber, communityId)
        // 贷款信息
        def mortgageList = MortgageCollateral.findAllByCollateral(collateral)*.mortgage
        respond estate, model: [params: params, mortgageList: mortgageList, estateDetail: estate, community: community['data'], communityPicArr: communityPicArr['data'], saleList: saleList['data'], listings: listings['data']]
    }

    def communityPic()
    {
        def id = params['id']
        def estate = Estate.findById(id)
        def communityPicArr = apiService.picture(estate.city.zoneNumber, estate.communityId, 5, 3)
        println(communityPicArr)
        respond communityPicArr, model: [communityPicArr: communityPicArr['data']], view: 'showPhoto'
    }

    def create()
    {
        respond new Estate(params)
    }

    @Transactional
    def save(Estate estate)
    {
        if (estate == null)
        {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        if (estate.hasErrors())
        {
            transactionStatus.setRollbackOnly()
            respond estate.errors, view: 'create'
            return
        }

        estate.save flush: true

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.created.message', args: [message(code: 'estate.label', default: 'Estate'), estate.id])
                redirect estate
            }
            '*' { respond estate, [status: CREATED] }
        }
    }

    def edit(Estate estate)
    {
        respond estate
    }

    @Transactional
    def update(Estate estate)
    {
        if (estate == null)
        {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        if (estate.hasErrors())
        {
            transactionStatus.setRollbackOnly()
            respond estate.errors, view: 'edit'
            return
        }

        estate.save flush: true

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.updated.message', args: [message(code: 'estate.label', default: 'Estate'), estate.id])
                redirect estate
            }
            '*' { respond estate, [status: OK] }
        }
    }

    @Transactional
    def delete(Estate estate)
    {

        if (estate == null)
        {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        estate.delete flush: true

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.deleted.message', args: [message(code: 'estate.label', default: 'Estate'), estate.id])
                redirect action: "index", method: "GET"
            }
            '*' { render status: NO_CONTENT }
        }
    }

    protected void notFound()
    {
        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.not.found.message', args: [message(code: 'estate.label', default: 'Estate'), params.id])
                redirect action: "index", method: "GET"
            }
            '*' { render status: NOT_FOUND }
        }
    }

    def searchEstate()
    {
        // 从聚合图进入押品列表页，渲染城市和区县
        if (params["communityId"])
        {
            def cityNumber = Estate.findByCommunityId(params["communityId"])?.city?.zoneNumber
            if (cityNumber)
            {
                params['city'] = cityNumber
            }
            def districtNumber = Estate.findByCommunityId(params["communityId"])?.district?.zoneNumber
            if (districtNumber)
            {
                params['district'] = districtNumber
            }
        }
        if (params["buildingId"])
        {
            def cityNumber = Estate.findByBuildingId(params["buildingId"])?.city?.zoneNumber
            if (cityNumber)
            {
                params['city'] = cityNumber
            }
            def districtNumber = Estate.findByBuildingId(params["buildingId"])?.district?.zoneNumber
            if (districtNumber)
            {
                params['district'] = districtNumber
            }
        }
        if (!params['city'])
        {
            params["city"] = '440100'
        }
        def order = params["order"]
        def sort = params["sort"]
        def city = params["city"]
        //城市
        def district = params["district"]
        //行政区
        def loansBalanceStart = params["loansBalanceStart"]
        //贷款余额
        def loansBalanceEnd = params["loansBalanceEnd"]
        //贷款余额
        def loansAmountStart = params["loansAmountStart"]
        //贷款金额
        def loansAmountEnd = params["loansAmountEnd"]
        //贷款金额
        def sourceAddress = params["sourceAddress"]
        //房屋坐落
        def startDateStart = params["startDateStart"]
        //放款时间
        def startDateEnd = params["startDateEnd"]
        //放款时间
        def loansDuration = params["loansDuration"]
        //贷款时间
        def remainTime = params["remainTime"]
        //剩余贷款时长
        def risk = params['risk']
        def buildAreaStart = params['buildAreaStart']
        def buildAreaEnd = params['buildAreaEnd']
        def accountId = params['accountId']
        //受理网点
        def residentialType = params['residentialType']
        //房屋用途
        def isEstate = params['isEstate']
        //押品状态
        def buildingId = params['buildingId']
        //楼栋Id
        def communityId = params['communityId']
        //小区ID
        def createdDateStart = params['createdDateStart']
        def createdDateEnd = params['createdDateEnd']
        def province = params["province"]
        def user = User.findById(springSecurityService.principal.id)
        //登录用户
        def userAccount = user.account
        //用户所属机构
        def estateList = new ArrayList()
        def accountQueryParam = new HashMap()
        def accountManageAccountSql = " select o.manageAccount from AccountManageAccount o where 1=1 "
        if (userAccount)
        {
            def id = userAccount.id
            accountManageAccountSql += " and o.account.id = :id "
            accountQueryParam['id'] = id
        }
        def accountManageAccountList = AccountManageAccount.executeQuery(accountManageAccountSql, accountQueryParam)
        if (!accountManageAccountList)
        {
            respond estateList, view: 'search'
            return
        }
        def estateQueryParam = new HashMap()
        String estateSql = " from Estate  e where 1=1 "
        estateSql = Estate.FilterAccount(estateSql, estateQueryParam, user)
        if (accountId && accountId != "")
        {
            estateSql += " and e.account.id = :accountId "
            estateQueryParam['accountId'] = Long.parseLong(accountId)
        }
        if (city && city != 'null' && city != '-1')
        {
            estateSql += " and e.city.zoneNumber = :city "
            estateQueryParam['city'] = city
        }
        if (province && province != '-1')
        {
            estateSql += " and e.province.name = :province "
            estateQueryParam['province'] = province
        }
        if (district && district != 'null' && district != '-1')
        {
            estateSql += "and e.district.zoneNumber = :district "
            estateQueryParam['district'] = district
        }
        if (loansBalanceStart && loansBalanceStart != '')
        {
            estateSql += "and e.loansBalance >= :loansBalanceStart "
            estateQueryParam['loansBalanceStart'] = new BigDecimal(loansBalanceStart) * 10000
        }
        if (loansBalanceEnd && loansBalanceEnd != '')
        {
            estateSql += "and e.loansBalance <= :loansBalanceEnd "
            estateQueryParam['loansBalanceEnd'] = new BigDecimal(loansBalanceEnd) * 10000
        }
        if (loansAmountStart && loansAmountStart != '')
        {
            estateSql += "and e.loansAmount >= :loansAmountStart "
            estateQueryParam['loansAmountStart'] = new BigDecimal(loansAmountStart) * 10000
        }
        if (loansAmountEnd && loansAmountEnd != '')
        {
            estateSql += "and e.loansAmount <= :loansAmountEnd "
            estateQueryParam['loansAmountEnd'] = new BigDecimal(loansAmountEnd) * 10000
        }
        if (sourceAddress && sourceAddress != '')
        {
            estateSql += "and e.sourceAddress like :sourceAddress "
            estateQueryParam['sourceAddress'] = '%' + sourceAddress + '%'
        }
        if (startDateStart)
        {
            //中文日期转换
            def dateStart = DateUtil.GetDateBeginByDateStr(startDateStart)
            estateSql += "and e.startDate >=  :dateStart "
            estateQueryParam['dateStart'] = dateStart
        }
        if (startDateEnd)
        {
            //中文日期转换
            def dateEnd = DateUtil.GetNextDateBeginByDateStr(startDateEnd)
            estateSql += "and e.startDate <  :dateEnd "
            estateQueryParam['dateEnd'] = dateEnd
        }
        if (createdDateStart)
        {
            //中文日期转换
            def createdDateStarts = DateUtil.GetDateBeginByDateStr(createdDateStart)
            estateSql += "and e.createdDate >=  :createdDateStarts "
            estateQueryParam['createdDateStarts'] = createdDateStarts
        }
        if (createdDateEnd)
        {
            //中文日期转换
            def createdDateEnds = DateUtil.GetNextDateBeginByDateStr(createdDateEnd)
            estateSql += "and e.createdDate <  :createdDateEnds "
            estateQueryParam['createdDateEnds'] = createdDateEnds
        }
        if (loansDuration && loansDuration != '')
        {
            def yearList = YearLimitDimension.list()
            yearList.each {
                if (it?.label == loansDuration)
                {
                    def loansDurationMin = it.minValue
                    def loansDurationMax = it.maxValue
                    estateSql += " and e.loansDuration > :loansDurationMin and e.loansDuration<= :loansDurationMax "
                    estateQueryParam['loansDurationMin'] = loansDurationMin
                    estateQueryParam['loansDurationMax'] = loansDurationMax
                }
            }
        }
        if (remainTime && remainTime != '')
        {
            def yearList = YearLimitDimension.list()
            yearList.each {
                if (it?.label == remainTime)
                {
                    def remainTimeMin = it.minValue
                    def remainTimeMax = it.maxValue
                    estateSql += " and e.remainTime > :remainTimeMin and e.remainTime<= :remainTimeMax "
                    estateQueryParam['remainTimeMin'] = remainTimeMin
                    estateQueryParam['remainTimeMax'] = remainTimeMax
                }
            }
        }
        if (risk && risk != '')
        {
            def riskList = RiskDimension.list()
            riskList.each {
                if (it?.label == risk)
                {
                    def minValue = it.minValue / 100
                    def maxValue = it.maxValue / 100
                    estateSql += " and e.cltv > :minValue and e.cltv<= :maxValue "
                    estateQueryParam['minValue'] = minValue
                    estateQueryParam['maxValue'] = maxValue
                }
            }
        }
        if (buildAreaStart && buildAreaStart != '')
        {
            estateSql += " and e.buildArea >= :buildAreaStart "
            estateQueryParam['buildAreaStart'] = new BigDecimal(buildAreaStart)
        }

        if (buildAreaEnd && buildAreaEnd != '')
        {
            estateSql += " and e.buildArea <= :buildAreaEnd "
            estateQueryParam['buildAreaEnd'] = new BigDecimal(buildAreaEnd)
        }
        if (residentialType && residentialType != '')
        {
            estateSql += " and e.buildingType.code = :residentialType "
            estateQueryParam['residentialType'] = residentialType
        }
        if (isEstate && isEstate != '')
        {
            estateSql += " and e.isEstate = :isEstate "
            estateQueryParam['isEstate'] = Boolean.parseBoolean(isEstate)
        }
        if (buildingId && buildingId != '-1')
        {
            estateSql += " and e.buildingId = :buildingId "
            estateQueryParam['buildingId'] = Long.parseLong(buildingId)
        }
        if (communityId && communityId != '-1')
        {
            estateSql += " and e.communityId = :communityId "
            estateQueryParam['communityId'] = Long.parseLong(communityId)
        }

        //查询总数
        String countSql = "select count(e.id) " + estateSql
        if (order && sort)
        {
            estateSql += " order by e.${sort} ${order}"
        }
        else
        {
            estateSql += "order by e.id desc "
        }

        city = params['city']

        estateList = Estate.findAll(estateSql, estateQueryParam, [max: params.max ?: 10, offset: params.offset ?: 0])
        def count = Estate.executeQuery(countSql, estateQueryParam)
        def districtList = District.findAllByParentAreaAndAreaLevel(City.findByZoneNumberAndAreaLevel(city, 2), 3)

        respond estateList, model: [estateCount: count[0], districtList: districtList, params: params, accountManageAccountList: accountManageAccountList], view: 'search'
    }

    def grade()
    {
        respond view: "grade"
    }

    def districtList()
    {
        if (params["city"] == '-1')
        {
            return '';
        }
        else
        {
            render([districtList: District.executeQuery(" from  District d where " + "" + "d.parentArea.zoneNumber='${params["city"]}'")] as JSON)
        }
    }

    def gradeContent()
    {

        def zoneNumber = params['city']
        def communityId = Long.parseLong(params['communityId'].toString())
        // 获取当月时间
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd")
        def cale = Calendar.getInstance();
        cale.add(Calendar.MONTH, 0);
        cale.set(Calendar.DAY_OF_MONTH, 1);
        def currentMonth = format.format(cale.getTime());
        // 获取上月时间
        def cale1 = Calendar.getInstance();
        cale1.add(Calendar.MONTH, -1);
        cale1.set(Calendar.DAY_OF_MONTH, 1);
        def lastMonth = format.format(cale1.getTime());

        // 获取三个月前时间
        def cale2 = Calendar.getInstance();
        cale2.add(Calendar.MONTH, -3);
        cale2.set(Calendar.DAY_OF_MONTH, 1);
        def threeMonth = format.format(cale2.getTime());

        //小区详情
        def community = apiService.community(zoneNumber, communityId)

        //成交案例列表
        def saleList = apiService.sale(zoneNumber, communityId)
        //评级
        def communityRiskRank = CommunityRiskRank.findById(communityId)
        //租售比
        def communityRentalRatio = CommunityRentalRatio.findByCommunityIdAndStatsDate(communityId, currentMonth)
        // 价格环比
        def communityPriceIndex = CommunityPriceIndex.findByCommunityIdAndStatsDate(communityId, currentMonth)
        //三个月前价格指数
        def threeCommunityPriceIndex = CommunityPriceIndex.findByCommunityIdAndStatsDate(communityId, threeMonth)
        def threeMonthPriceIndex = 0
        if (threeCommunityPriceIndex != null && communityPriceIndex != null)
        {
            threeMonthPriceIndex = communityPriceIndex?.communityIndex - threeCommunityPriceIndex?.communityIndex
        }

        //价格趋势
        def communityPrice = CommunityPrice.findByCommunityIdAndStatsDate(communityId, currentMonth)


        //成交量
        def communityQuantityRisk = CommunityQuantityRisk.findByCommunityIdAndStatsDate(communityId, currentMonth)
        //上月成交量
        def lastCommunityQuantityRisk = CommunityQuantityRisk.findByCommunityIdAndStatsDate(communityId, lastMonth)
        //成交周期
        def communityDealCycle = CommunityDealCycle.findByCommunityIdAndStatsDate(communityId, currentMonth)

        render model: [community: community['data'], saleList: saleList["data"], communityRiskRank: communityRiskRank,
            communityRentalRatio: communityRentalRatio, communityPrice: communityPrice,
            communityDealCycle: communityDealCycle, communityQuantityRisk: communityQuantityRisk,
            lastCommunityQuantityRisk: lastCommunityQuantityRisk, threeMonthPriceIndex: threeMonthPriceIndex,
            communityPriceIndex: communityPriceIndex],
               view: 'gradeContent'
    }

    /**
     * 价格趋势数据
     * @return
     */
    def priceData()
    {
        def communityId = params['communityId']
        def communityPrices = CommunityPrice.findAllByCommunityId(communityId, [sort: 'statsDate',
            order: 'asc']).asList()
        render([communityPrices: communityPrices] as JSON)
    }

    /**
     * 租售比趋势数据
     * @return
     */
    def ratioData()
    {
        def communityId = params['communityId']
        def communityRentalRatios = CommunityRentalRatio.findAllByCommunityId(communityId, [sort: 'statsDate',
            order: 'asc']).asList()
        render([communityRentalRatios: communityRentalRatios] as JSON)
    }

    /**
     * 成交量趋势数据
     * @return
     */
    def saleData()
    {
        def communityId = params['communityId']
        def communityQuantityRisks = CommunityQuantityRisk.findAllByCommunityId(communityId, [sort: 'statsDate',
            order: 'asc'])
            .asList()
        render([communityQuantityRisks: communityQuantityRisks] as JSON)
    }

    /**
     * 模糊查询小区名（打分卡页面专用）
     * @return
     */
    def searchCommunity()
    {
        def communityName = params['communityName']
        def list = CommunityRiskRank.findAllByNameLike("%${communityName}%")
        render([list: list] as JSON)
    }

    // ******************************押品登记管理***************************************************

    def estateIndex()
    {

        def max = Math.min(params.max ? params.max.toInteger() : 10, 100)
        def offset = params.offset ? params.offset.toInteger() : 0
        def city = params["city"]
        def district = params["district"]
        def estateStatus = params["estateStatus"]
        def name = params["name"]
        def sourceAddress = params["sourceAddress"]
        def risk = params["risk"]
        def buildAreaStart = params["buildAreaStart"]
        def buildAreaEnd = params["buildAreaEnd"]
        def buildingType = params["buildingType"]
        def cashability = params["cashability"]
        def createdDateStart = params['createdDateStart']
        def createdDateEnd = params['createdDateEnd']
        def province = params["province"]
        def externalId = params["externalId"]
        def stage = params["stage"]
        def status = params['status'] ? params['status'] : "Pending"

        def estateQueryParam = new HashMap()
        def user = User.findById(springSecurityService.principal.id)
        def estateSql = " from Collateral e where e.status = '${status}' and e.type.code = 'estate'"
        def sql = " "
        if (city && city != "-1")
        {
            sql += " and e.city.zoneNumber = :city "
            estateQueryParam['city'] = city
        }
        if (district && district != "-1")
        {
            sql += " and e.district.zoneNumber = :district"
            estateQueryParam['district'] = district
        }
        if (estateStatus && estateStatus != "")
        {
            sql += " and e.estateStatus.id = :estateStatus"
            estateQueryParam['estateStatus'] = Long.parseLong(estateStatus)
        }
        if (name && name != "")
        {
            sql += " and e.name like :name "
            estateQueryParam['name'] = '%' + name + '%'
        }
        if (sourceAddress && sourceAddress != "")
        {
            sql += " and e.estate.sourceAddress like :sourceAddress "
            estateQueryParam['sourceAddress'] = '%' + sourceAddress + '%'
        }
        if (risk && risk != "")
        {
            def riskList = RiskDimension.list()
            riskList.each {
                if (it?.label == risk)
                {
                    def minValue = it.minValue / 100
                    def maxValue = it.maxValue / 100
                    sql += " and e.cltv > :minValue and e.cltv <= :maxValue "
                    estateQueryParam['minValue'] = minValue
                    estateQueryParam['maxValue'] = maxValue
                }
            }
        }
        if (buildAreaStart && buildAreaStart != '')
        {
            sql += " and e.estate.buildArea >= :buildAreaStart "
            estateQueryParam['buildAreaStart'] = new BigDecimal(buildAreaStart)
        }

        if (buildAreaEnd && buildAreaEnd != '')
        {
            sql += " and e.estate.buildArea <= :buildAreaEnd "
            estateQueryParam['buildAreaEnd'] = new BigDecimal(buildAreaEnd)
        }
        if (buildingType && buildingType != "")
        {
            sql += " and e.estate.buildingType.id = :buildingType "
            estateQueryParam['buildingType'] = Long.parseLong(buildingType)
        }
        if (cashability && cashability != "")
        {
            sql += " and e.cashability.id = :cashability "
            estateQueryParam['cashability'] = Long.parseLong(cashability)
        }
        if (province && province != '-1')
        {
            sql += " and e.estate.province.name = :province "
            estateQueryParam['province'] = province
        }
        if (createdDateStart)
        {
            //中文日期转换
            def createdDateStarts = DateUtil.GetDateBeginByDateStr(createdDateStart)
            sql += "and e.estate.createdDate >=  :createdDateStarts "
            estateQueryParam['createdDateStarts'] = createdDateStarts
        }
        if (createdDateEnd)
        {
            //中文日期转换
            def createdDateEnds = DateUtil.GetNextDateBeginByDateStr(createdDateEnd)
            sql += "and e.estate.createdDate <  :createdDateEnds "
            estateQueryParam['createdDateEnds'] = createdDateEnds
        }
        if (externalId && externalId != "")
        {
            sql += " and e.externalId like :externalId "
            estateQueryParam['externalId'] = '%' + externalId + '%'
        }
        if (stage && stage != "")
        {
            sql += " and e.stage.id = :stage "
            estateQueryParam['stage'] = Long.parseLong(stage)
        }

        def countSql = " select count(e.id) from Collateral e where e.status = '${status}' and e.type.code = 'estate' "
        countSql += sql
        sql += " order by e.externalId desc "
        estateSql += sql
        def collateralList = Collateral.executeQuery(estateSql, estateQueryParam, [max: max, offset: offset])
        def collateralCount = Collateral.executeQuery(countSql, estateQueryParam)
        def districtList = District.findAllByParentAreaAndAreaLevel(City.findByZoneNumberAndAreaLevel(city, 2), 3)
        respond collateralList, model: [collateralList: collateralList, collateralCount: collateralCount[0], districtList: districtList, params: params]
    }

    def estateCreate()
    {
        def collateralId = params['collateralId']
        respond new Estate(params), model: [collateralId: collateralId]
    }

    @Transactional
    def estateSave(Estate estate)
    {
        def collateralId = params['collateralId']


        if (estate == null)
        {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        if (estate.hasErrors())
        {
            transactionStatus.setRollbackOnly()
            respond estate.errors, view: 'estateCreate'
            return
        }

        //根据押品外部编号验证唯一性
        if (Estate.findByExternalId(estate.externalId) || Collateral.findByExternalId(estate.externalId))
        {
            transactionStatus.setRollbackOnly()
            flash.message = "押品 '" + estate.externalId + "' 已存在"
            respond estate, view: 'estateCreate'
            return
        }

        //获取地址拆分信息
        def newEstate = addressSplit(estate)
        newEstate.save flush: true

        def newCollateral = Collateral.findByEstate(newEstate)


        if (collateralId)
        {
            //如果是替换押品,创建互相关联关系

            def oldCollateral = Collateral.findById(Long.parseLong(collateralId))
            oldCollateral.replacementCollateral = newCollateral
            //旧押品状态设置  TODO
            oldCollateral.save flush: true

            newCollateral.replacementCollateral = oldCollateral
            //新押品状态设置  TODO
            newCollateral.save flush: true

            def param = [em: "1",
                city: newCollateral?.estate?.city?.name,
                name: newCollateral?.estate?.communityName,
                address: newCollateral?.estate?.sourceAddress,
                floor: newCollateral?.estate?.sourceCurrentFloor,
                totalfloor: newCollateral?.estate?.sourceTotalFloor,
                square: newCollateral?.estate?.loadArea,
                buildingYear: newCollateral?.estate?.buildYear]
            def communityId = estate?.communityId
            //判断地址拆分是否返回小区id，如果没有代表拆分失败，流程终止
            if (communityId && communityId != "-1")
            {
                // 评估
                def result = apiService.assess(param)
                println "评估结果:" + result

                newCollateral.unitPrice = result?.unitprice
                newCollateral.totalPrice = result?.saleprice

                if (result?.evaluateDate)
                {
                    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
                    newCollateral.valuationDate = format.parse(result?.evaluateDate)
                }
                else
                {
                    newCollateral.valuationDate = new Date()
                }
                newCollateral.save flush: true
            }
            redirect(action: 'estateShow', params: [id: oldCollateral.id])
            return
        }

        // 初始化工作流
        collateralService.initCollateralFlowStage(newCollateral)

        redirect(action: 'estateShow', params: [id: newCollateral.id])
    }

    def estateShow(Collateral collateral)
    {
        def estate = collateral?.estate
        def replaceCollateral = collateral?.replacementCollateral
        def zoneNumber = estate.city.zoneNumber
        def communityId = estate.communityId
        //小区详情
        def community = apiService.community(zoneNumber, communityId)
        //小区照片
        def communityPicArr = apiService.picture(zoneNumber, communityId, 5, 3)
        //成交案例列表
        def saleList = apiService.sale(zoneNumber, communityId)
        //挂牌案例列表
        def listings = apiService.listing(zoneNumber, communityId)
        // 贷款信息
        def mortgageList = MortgageCollateral.findAllByCollateral(collateral)*.mortgage

        def user = User.findById(springSecurityService.principal.id)
        def flowStage = CollateralFlowStage.findByCollateralAndStage(collateral, collateral?.stage)
        def roleSql = ""
        def roleList = UserRole.findAllByUser(user)*.role
        if (roleList)
        {
            String roleIdList = roleList*.id?.toString()
            roleSql += " and role.id in (" + roleIdList?.substring(1, roleIdList.lastIndexOf("]")) + ")"
        }
        def editRoleFlag = false
        def approveRoleFlag = false
        if (flowStage)
        {
            editRoleFlag = CollateralFlowStageRole.find("from CollateralFlowStageRole where flowStage.id = ? and teamRole.id = ? " + roleSql, [flowStage?.id, TeamRole.EDIT()?.id]) && true
            approveRoleFlag = CollateralFlowStageRole.find("from CollateralFlowStageRole where flowStage.id = ? and teamRole.id = ? " + roleSql, [flowStage?.id, TeamRole.APPROVAL()?.id]) && true
        }

        def layout = CollateralFlowStage.findByCollateralAndStage(collateral, collateral?.stage)?.layout?.name
        respond collateral, model: [editRoleFlag: editRoleFlag, approveRoleFlag: approveRoleFlag, params: params, mortgageList: mortgageList, estateDetail: estate, replaceCollateral: replaceCollateral, community: community['data'], communityPicArr: communityPicArr['data'], saleList: saleList['data'], listings: listings['data']], view: layout
    }

    def estateEdit(Estate estate)
    {
        respond estate
    }

    @Transactional
    def estateUpdate(Estate estate)
    {
        if (estate == null)
        {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        if (estate.hasErrors())
        {
            transactionStatus.setRollbackOnly()
            respond estate.errors, view: 'edit'
            return
        }

        estate.save flush: true

        def collateral = Collateral.findByEstate(estate)
        collateral.province = estate.province
        collateral.city = estate.city
        collateral.district = estate.district
        collateral.estateStatus = estate.estateStatus
        collateral.isEstate = estate.isEstate
        collateral.unitPrice = estate.unitPrice
        collateral.totalPrice = estate.totalPrice
        collateral.valuationDate = estate.valuationDate
        collateral.ltv = estate.ltv
        collateral.cltv = estate.cltv
        collateral.account = estate.account
        collateral.externalId = estate.externalId
        collateral.name = estate.name
        collateral.fullName = estate.fullName
        collateral.identityType = estate.identityType
        collateral.idNumber = estate.idNumber
        collateral.loanCardNumber = estate.loanCardNumber
        collateral.commonOwnerFullName = estate.commonOwnerFullName
        collateral.sharePoint = estate.sharePoint
        collateral.cashability = estate.cashability
        collateral.valueVolatility = estate.valueVolatility
        collateral.seizureOfConvenience = estate.seizureOfConvenience
        collateral.relationOfMortgagor = estate.relationOfMortgagor
        collateral.legalValidity = estate.legalValidity
        collateral.firstEvaluatePrice = estate.firstEvaluatePrice
        collateral.firstEvaluateAccount = estate.firstEvaluateAccount
        collateral.latestEvaluatePrice = estate.latestEvaluatePrice
        collateral.latestEvaluateAccount = estate.latestEvaluateAccount
        collateral.latestEvaluateDate = estate.latestEvaluateDate
        collateral.nextEvaluateDate = estate.nextEvaluateDate
        collateral.actualMortgageRate = estate.actualMortgageRate
        collateral.mortgageRateUpperLimit = estate.mortgageRateUpperLimit
        collateral.description = estate.description
        collateral.registerFullName = estate.registerFullName
        collateral.registerAccount = estate.registerAccount
        collateral.registerDate = estate.registerDate
        collateral.registerUpdateDate = estate.registerUpdateDate
        collateral.estate = estate
        collateral.type = CollateralType.findByCode("estate")
        collateral.sourceClass = "estate"

        if (collateral.validate())
        {
            collateral.save()
        }
        else
        {
            println collateral.errors
        }

        redirect(action: 'estateShow', params: [id: collateral.id])
    }

    def addressSplit(Estate estate)
    {
        println "地址：" + estate?.city?.name + estate?.sourceAddress
        def result = new HashMap()
        def addressSplitList = splitMatchApiService.splitMatch(estate?.city?.name, estate?.sourceAddress)
        def communityId = addressSplitList?.match_community_id
        if (communityId && communityId != "-1")
        {
            estate.communityId = addressSplitList?.match_community_id?.toInteger()
            estate.communityName = addressSplitList?.match_community_name
            estate.buildingId = addressSplitList?.match_building_id?.toInteger()
            estate.buildingName = addressSplitList?.match_building_name
            estate.unitId = addressSplitList?.match_unit_id?.toInteger()
            estate.unitName = addressSplitList?.match_unit_name
            estate.houseId = addressSplitList?.match_house_id?.toInteger()
            estate.houseName = addressSplitList?.match_house_name
            estate.streetId = addressSplitList?.match_street_id?.toInteger()
            estate.streetName = addressSplitList?.match_street_name
        }
        else
        {
            result['code'] = "-1"
            result['message'] = "地址拆分失败"
        }
        print "result:" + result
        return estate
    }

    // 登记流程推进
    def approve(Collateral collateral)
    {
        def user = User.findById(springSecurityService.principal.id)
        def flowStage = CollateralFlowStage.findByCollateralAndStage(collateral, collateral?.stage)
        def roleSql = ""
        def roleList = UserRole.findAllByUser(user)*.role
        if (roleList)
        {
            String roleIdList = roleList*.id?.toString()
            roleSql += " and role.id in (" + roleIdList?.substring(1, roleIdList.lastIndexOf("]")) + ")"
        }

        def approveRoleFlag = CollateralFlowStageRole.find("from CollateralFlowStageRole where flowStage.id = ? and teamRole.id = ? " + roleSql, [flowStage?.id, TeamRole.APPROVAL()?.id]) && true
        if (!approveRoleFlag)
        {
            flash.message = "权限校验失败"
            redirect action: 'estateShow', id: collateral?.id
            return
        }

        // 校验是否提交备注
        def comment = Comment.findByCollateralAndStage(collateral, collateral?.stage)
        if (!comment)
        {
            flash.message = "未提交审批意见"
            redirect action: 'estateShow', id: collateral?.id
            return
        }

        def map = collateralService.approve(collateral)
        if (!map['flag'])
        {
            flash.message = map['message']
            redirect action: 'estateShow', id: collateral?.id
            return
        }

        redirect action: 'estatePendingIndex'
    }

    def reject(Collateral collateral)
    {
        def user = User.findById(springSecurityService.principal.id)
        def flowStage = CollateralFlowStage.findByCollateralAndStage(collateral, collateral?.stage)
        def roleSql = ""
        def roleList = UserRole.findAllByUser(user)*.role
        if (roleList)
        {
            String roleIdList = roleList*.id?.toString()
            roleSql += " and role.id in (" + roleIdList?.substring(1, roleIdList.lastIndexOf("]")) + ")"
        }

        def approveRoleFlag = CollateralFlowStageRole.find("from CollateralFlowStageRole where flowStage.id = ? and teamRole.id = ? " + roleSql, [flowStage?.id, TeamRole.APPROVAL()?.id]) && true
        if (!approveRoleFlag)
        {
            flash.message = "权限校验失败"
            redirect action: 'estateShow', id: collateral?.id
            return
        }

        def canReject = collateralService.reject(collateral)
        if (canReject)
        {
            def comment = new Comment()
            comment.collateral = collateral
            comment.stage = collateral?.stage
            comment.comment = params['comment']
            comment.save flush: true

            redirect action: 'estatePendingIndex'
        }
        else
        {
            flash.message = "对不起，无权限拒绝"
            redirect action: 'estateShow', id: collateral?.id
            return
        }
    }

    def related()
    {
    }

    @Transactional
    def doRelated()
    {
        def mortgegeId = params['mortgageId']
        def collateralId = params['collateralId']
        //如果贷款合同号无效 不处理
        def mortgage = Mortgage.findById(Long.parseLong(mortgegeId))
        def collateral = Collateral.findById(Long.parseLong(collateralId))
        println mortgage
        println collateral
        if (mortgage == null || collateral == null)
        {
            return
        }

        def mortgageCollateral = new MortgageCollateral()
        mortgageCollateral.collateral = collateral
        mortgageCollateral.mortgage = mortgage
        mortgageCollateral.save flush: true
        redirect action: "estateShow", controller: "estate", params: [id: collateral?.id]
    }

    @Transactional
    def updateContract(Contract contract)
    {
        def mortgege_id = params['mortgageId']

        //如果贷款合同号无效 不处理
        def mortgage = Mortgage.findById(Long.parseLong(mortgege_id))
        if (mortgage == null)
        {
            return
        }

        if (contract == null)
        {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        if (contract.hasErrors())
        {
            println contract.errors
            transactionStatus.setRollbackOnly()
            respond contract.errors, view: 'create'
            return
        }

        contract.save flush: true

        redirect action: "show", controller: "mortgage", params: [id: mortgage?.id]
    }

    //    def outOfStorage(Collateral collateral)
    //    {
    //        def targetUri = request.getHeader("referer")
    //        def status="success"
    //        try{
    //            def stage = CollateralStage.findById(params['stage'])
    //            collateral.stage = stage
    //            collateral.status = "Pending"
    //            collateral.save()
    //        }catch (Exception e){
    //            e.printStackTrace()
    //            status="false"
    //        }
    //        render([status: status, targetUri: targetUri] as JSON)
    //    }

    def outOfStorage(Collateral collateral)
    {
        def targetUri = request.getHeader("referer")
        def status = "success"
        def workFlowId = params['workFlowId']
        println workFlowId
        try
        {
            def collateralWorkFlow = Workflow.findById(workFlowId)
            println collateralWorkFlow
            //初始化工作流
            collateralService.initCollateralFlowStage(collateral, collateralWorkFlow)
        }
        catch (Exception e)
        {
            e.printStackTrace()
            status = "false"
        }
        render([status: status, targetUri: targetUri] as JSON)
    }

    def isEstateExist()
    {
        def flag = false
        if (Collateral.findByExternalId(params['externalId']))
        {
            flag = true
        }
        render([status: "success", flag: flag] as JSON)
    }

    @Transactional
    def changeCollateralStatus(Collateral collateral)
    {
        collateral.status = "Failed"
        collateral.descriptionOfFailure = params['descriptionOfFailure']
        collateral.save flush: true

        redirect action: 'estateShow', params: [id: collateral?.id]
    }

    def estatePendingIndex()
    {
        def max = Math.min(params.max ? params.max.toInteger() : 10, 100)
        def offset = params.offset ? params.offset.toInteger() : 0

        def city = params["city"]
        def district = params["district"]
        def estateStatus = params["estateStatus"]
        def name = params["name"]
        def sourceAddress = params["sourceAddress"]
        def risk = params["risk"]
        def buildAreaStart = params["buildAreaStart"]
        def buildAreaEnd = params["buildAreaEnd"]
        def buildingType = params["buildingType"]
        def cashability = params["cashability"]
        def createdDateStart = params['createdDateStart']
        def createdDateEnd = params['createdDateEnd']
        def province = params["province"]
        def externalId = params["externalId"]
        def stage = params["stage"]
        def status = params['status'] ? params['status'] : 'Pending'

        def roleSql = ""
        def user = User.findById(springSecurityService.principal.id)
        def roleList = UserRole.findAllByUser(user)*.role
        if (roleList)
        {
            String roleIdList = roleList*.id?.toString()
            roleSql += " and role.id in (" + roleIdList?.substring(1, roleIdList.lastIndexOf("]")) + ")"
        }

        def estateQueryParam = new HashMap()
        def estateSql = "select f.collateral from CollateralFlowStage f left join f.collateral c where f.stage.id = c.stage.id and f.id in (select flowStage.id from CollateralFlowStageRole where teamRole.code = 'Approval'" + roleSql + ") and c.status = '${status}' and c.type.code = 'estate'"
        def sql = " "
        if (city && city != "-1")
        {
            sql += " and c.city.zoneNumber = :city "
            estateQueryParam['city'] = city
        }
        if (district && district != "-1")
        {
            sql += " and c.district.zoneNumber = :district"
            estateQueryParam['district'] = district
        }
        if (estateStatus && estateStatus != "")
        {
            sql += " and c.estateStatus.id = :estateStatus"
            estateQueryParam['estateStatus'] = Long.parseLong(estateStatus)
        }
        if (name && name != "")
        {
            sql += " and c.name like :name "
            estateQueryParam['name'] = '%' + name + '%'
        }
        if (sourceAddress && sourceAddress != "")
        {
            sql += " and c.estate.sourceAddress like :sourceAddress "
            estateQueryParam['sourceAddress'] = '%' + sourceAddress + '%'
        }
        if (risk && risk != "")
        {
            def riskList = RiskDimension.list()
            riskList.each {
                if (it?.label == risk)
                {
                    def minValue = it.minValue / 100
                    def maxValue = it.maxValue / 100
                    sql += " and c.cltv > :minValue and c.cltv <= :maxValue "
                    estateQueryParam['minValue'] = minValue
                    estateQueryParam['maxValue'] = maxValue
                }
            }
        }
        if (buildAreaStart && buildAreaStart != '')
        {
            sql += " and c.estate.buildArea >= :buildAreaStart "
            estateQueryParam['buildAreaStart'] = new BigDecimal(buildAreaStart)
        }

        if (buildAreaEnd && buildAreaEnd != '')
        {
            sql += " and c.estate.buildArea <= :buildAreaEnd "
            estateQueryParam['buildAreaEnd'] = new BigDecimal(buildAreaEnd)
        }
        if (buildingType && buildingType != "")
        {
            sql += " and c.estate.buildingType.id = :buildingType "
            estateQueryParam['buildingType'] = Long.parseLong(buildingType)
        }
        if (cashability && cashability != "")
        {
            sql += " and c.cashability.id = :cashability "
            estateQueryParam['cashability'] = Long.parseLong(cashability)
        }
        if (province && province != '-1')
        {
            sql += " and c.estate.province.name = :province "
            estateQueryParam['province'] = province
        }
        if (createdDateStart)
        {
            //中文日期转换
            def createdDateStarts = DateUtil.GetDateBeginByDateStr(createdDateStart)
            sql += "and c.estate.createdDate >=  :createdDateStarts "
            estateQueryParam['createdDateStarts'] = createdDateStarts
        }
        if (createdDateEnd)
        {
            //中文日期转换
            def createdDateEnds = DateUtil.GetNextDateBeginByDateStr(createdDateEnd)
            sql += "and c.estate.createdDate <  :createdDateEnds "
            estateQueryParam['createdDateEnds'] = createdDateEnds
        }
        if (externalId && externalId != "")
        {
            sql += " and c.externalId like :externalId "
            estateQueryParam['externalId'] = '%' + externalId + '%'
        }
        if (stage && stage != "")
        {
            sql += " and c.stage.id = :stage "
            estateQueryParam['stage'] = Long.parseLong(stage)
        }

        println estateSql + sql
        def countSql = "select count(c.id) from CollateralFlowStage f left join f.collateral c where f.stage.id = c.stage.id and f.id in (select flowStage.id from CollateralFlowStageRole where teamRole.code = 'Approval'" + roleSql + ") and c.status = '${status}' and c.type.code = 'estate'" + sql
        sql += " order by c.externalId desc "
        def collateralList = CollateralFlowStage.executeQuery(estateSql + sql, estateQueryParam, [max: max, offset: offset])
        def collateralCount = CollateralFlowStage.executeQuery(countSql, estateQueryParam)
        def districtList = District.findAllByParentAreaAndAreaLevel(City.findByZoneNumberAndAreaLevel(city, 2), 3)

        respond collateralList, model: [collateralList: collateralList, collateralCount: collateralCount[0], districtList: districtList, params: params], view: 'estatePendingIndex'
    }

    // @Transactional
    // def reEvaluate()
    // {
    //     println params

    //     def batch = params['batchNumber']
    //     def evaluateType = params['evaluateType']
    //     def latestEvaluateAccount = params['latestEvaluateAccountName']

    //     def estateImportBatch = EstateImportBatch.findById(batch)
    //     if (evaluateType == "1")
    //     {
    //         estateImportBatch.evaluateType = EvaluateDict.AUTOMATIC()
    //     }
    //     if (evaluateType == "7")
    //     {
    //         estateImportBatch.evaluateType = EvaluateDict.ARTIFICIAL()
    //     }
    //     if (evaluateType == "8")
    //     {
    //         estateImportBatch.evaluateType = EvaluateDict.AUTOANDARTIFICIAL()
    //     }
    //     if (evaluateType == "10")
    //     {
    //         estateImportBatch.evaluateType = EvaluateDict.EVALUATE()
    //     }

    //     estateImportBatch.latestEvaluateAccount = Account.findById(latestEvaluateAccount)
    //     estateImportBatch.status = ExecStatusDict.findByCode("2")
    //     estateImportBatch.matchNum = 0
    //     if (estateImportBatch.validate()) 
    //     {
    //         estateImportBatch.save flush: true
    //     }
    //     else
    //     {
    //         println estateImportBatch.errors
    //     }

    //     def estateImportList = EstateImport.findAllByBatch(estateImportBatch)
    //     estateImportList?.each
    //     {
    //         it?.latestEvaluateAccount = Account.findById(latestEvaluateAccount)
    //         it?.evaluateStatue = ExecStatusDict.findByCode("2")
    //         it?.totalPrice = null
    //         it?.evaluateDate = null
    //     }

    //     // 评估机构重估
    //     if (evaluateType != "10")
    //     {
    //         evaluateService.evaluateBatch(batch?.toInteger(), evaluateType?.toInteger())
    //     }

    //     redirect controller: 'estateImportBatch', action: 'index'
    // }
}


